<template>
  <div class="manage-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="客户名称:" prop="name">
        <el-input v-model.trim="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="客户组织" prop="organizationCode">
        <el-select
          v-model="form.organizationCode"
          placeholder="请选择客户组织"
          @change="selectDept($event)">
          <el-option label="请选择客户组织" value=""></el-option>
          <el-option
            v-for="item in deptList"
            :key="item.fnumber"
            :label="item.fname"
            :value="item.fnumber"
          ></el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="客户大分类" prop="customerTypeCode">-->
<!--        <el-select-->
<!--          v-model="form.customerTypeCode"-->
<!--          placeholder="请选择客户大分类"-->
<!--          @change="selectCustomerType($event)"-->
<!--        >-->
<!--          <el-option label="请选择客户大分类" value=""></el-option>-->
<!--          <el-option-->
<!--            v-for="item in customerTypeList"-->
<!--            :key="item.fid"-->
<!--            :label="item.fname"-->
<!--            :value="item.fid"-->
<!--          ></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="客户分类" prop="customerTypeCode">
        <el-select
          v-model="form.customerTypeCode"
          placeholder="请选择客户分类"
        >
          <el-option label="请选择客户分类" value=""></el-option>
          <el-option
            v-for="item in customerTypeList"
            :key="item.fnumber"
            :label="item.fnumber + '(' + item.fname + ')'"
            :value="item.fnumber"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务人员" prop="bizCode">
        <el-select v-model="form.bizCode" placeholder="请选择业务人员">
          <el-option label="请选择业务人员" value=""></el-option>
          <el-option
            v-for="item in bizList"
            :key="item.fnumber"
            :label="item.fname"
            :value="item.fnumber"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型" prop="customerKindCode">
        <el-select v-model="form.customerKindCode" placeholder="请选择客户类型">
          <el-option label="请选择客户类型" value=""></el-option>
          <el-option v-for="item in customerKindList" :key="item.no" :label="item.label" :value="item.no"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="principal">
        <el-input v-model.trim="form.principal" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item v-show="!form.id" label="密码" prop="password">
        <el-input
          v-model.trim="form.password"
          type="password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="!form.id" label="确认密码" prop="passwordConfirm">
        <el-input
          v-model.trim="form.passwordConfirm"
          type="password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input v-model.trim="form.phoneNumber" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="价格策略" prop="priceStrategy">
        <el-select v-model="form.priceStrategy" filterable>
          <el-option value="" label="请选择价格策略"></el-option>
          <el-option
            v-for="(item, index) in priceStrategyList"
            :key="index"
            :value="item.id"
            :label="item.strategyName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物流线路" prop="wuliuCode">
        <el-select v-model="form.wuliuCode" filterable>
          <el-option value="" label="请选择物流线路"></el-option>
          <el-option
            v-for="(item, index) in wuliuList"
            :key="index"
            :value="item.fnumber"
            :label="item.fdataValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="收款条件" prop="shoukuanCode">
        <el-select v-model="form.shoukuanCode" filterable>
          <el-option value="" label="请选择收款条件"></el-option>
          <el-option
            v-for="(item, index) in shoukuanList"
            :key="index"
            :value="item.fnumber"
            :label="item.fname"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="客户所属公司" prop="companyCode">
        <el-select v-model="form.companyCode" filterable>
          <el-option value="" label="请选择客户所属公司"></el-option>
          <el-option
            v-for="(item1, index) in companyList"
            :key="index"
            :value="item1.fnumber"
            :label="item1.fdatavalue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="物流排序" prop='wuliuOrder'>
        <el-input-number v-model='form.wuliuOrder' :precision='0' :min='0' :max='9999999'></el-input-number>
      </el-form-item>
      <el-form-item style="color: #a52a2a" >
        *装箱单根据物流排序从小到大进行制单
      </el-form-item>
      <el-form-item label="订单金额(元)" prop="orderQty">
        <el-select v-model="form.orderQty">
          <el-option value="0" label="请选择订单金额"></el-option>
          <el-option
            v-for="(item, index) in orderQtys"
            :key="index"
            :value="item"
            :label="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="color: #a52a2a" >
        *设定订单金额后，订单总金额低于此金额后，收取运费
      </el-form-item>
      <el-form-item label="运费" prop="freightFee">
        <el-input-number v-model="form.freightFee" :min="0" />
      </el-form-item>
      <el-form-item label="送货地址:">
        <div class="address">
          <div>
            <el-select
              v-model="selectProvince"
              filterable
              size="small"
              placeholder="请选择省份"
              @change="selectProvinceFun($event)"
            >
              <el-option value="" label="请选择省份"></el-option>
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :value="item"
                :label="item.value"
              ></el-option>
            </el-select>
          </div>
          <div>
            <el-select
              v-model="selectCity"
              filterable
              size="small"
              placeholder="请选择城市"
              @change="selectCityFun($event)"
            >
              <el-option value="" label="请选择城市"></el-option>
              <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :value="item"
                :label="item.value"
              ></el-option>
            </el-select>
          </div>
          <div>
            <el-select
              v-model="selectArea"
              filterable
              size="small"
              placeholder="请选择区县"
            >
              <el-option value="" label="请选择区县"></el-option>
              <el-option
                v-for="(item, index) in areaList"
                :key="index"
                :value="item"
                :label="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model.trim="form.address" autocomplete="off"></el-input>
      </el-form-item>
	  <el-form-item label="预付款金额" prop="depositAmount">
	    <el-input v-model.trim="form.depositAmount" type="number" autocomplete="off"></el-input>
	  </el-form-item>
	  <el-form-item label="锁定金额" prop="lockAmount">
	    <el-input v-model.trim="form.lockAmount" :disabled="true" type="number" autocomplete="off"></el-input>
	  </el-form-item>
	  <el-form-item label="预付模式" prop="noDepositOrder">
		<el-select v-model="form.noDepositOrder" placeholder="请选择预付模式">
		  <el-option label="请选预付模式" value=""></el-option>
		  <el-option label="正常模式" value="1"></el-option>
		  <el-option label="预付模式" value="2"></el-option>
		</el-select>
	  </el-form-item>
	  <el-form-item label="超预付额度" prop="overDepositOrder">
		<el-input v-model.trim="form.overDepositOrder" type="number" autocomplete="off"></el-input>
	  </el-form-item>
      <el-form-item label="审批权限" prop="approvedPermiss">
        <el-checkbox v-model="approvedPermiss"></el-checkbox>
      </el-form-item>
      <el-form-item label="报表查看" prop="reportViewPermiss">
        <el-checkbox v-model="reportViewPermiss"></el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import province from './region'
import {
  getDept,
  getCustomerLastTypeList,
  getCustomerTypeList,
  getCustomerTypeChildrenList,
  getBizList,
  getWuliuList,
  getShoukuanList,
  getCompanyList,
} from '@/api/erp'

import { approvedPermiss, reportViewPermiss } from '@/config/settings'

import {
  doEdit,
  doAdd,
  doCheckPhoneNumber,
  doCheckUserName,
} from '@/api/customerManagement'
import { getApprovedList } from '@/api/priceStrategyManagement'
export default {
  name: 'CustomerManagement',
  components: {},
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.form.confirmPassword !== '') {
          this.$refs.form.validateField('passwordConfirm')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    //检查手机号码
    let checkPhoneNumber = async (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码'))
      }

      let res = await doCheckPhoneNumber({
        id: this.form.id || 0,
        phoneNumber: value,
      })
      if (res) {
        return callback(new Error('该手机号码已经存在'))
      }
      return callback()
    }

    //检查手机号码
    let checkUserNumber = async (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名称'))
      }

      let res = await doCheckUserName({
        id: this.form.id || 0,
        name: value,
      })
      if (res) {
        return callback(new Error('该用户名称已经存在'))
      }
      return callback()
    }

    return {
      form: {
        id: '',
        name: '',
        organizationCode: '',
        organizationName: '',
        customerTypeCode: '',
        customerTypeName: '',
        customerTypeChildCode: '',
        customerTypeChildName: '',
        bizCode: '',
        bizName: '',
        customerKindCode: '',
        customerKindName: '',
        principal: '',
        priceStrategy: '',
        phoneNumber: '',
        province: '',
        city: '',
        district: '',
        address: '',
        password: '',
        passwordConfirm: '',
        permiss: 0,
        orderQty: '',
        wuliuCode: '',
        wuliuName: '',
        shoukuanCode:'',
        shoukuanName:'',
        companyCode:'',
        companyName:'',
        wuliuOrder:0,
        freight:0,
        freightFee:'',
		lockAmount:'',
		depositAmount : '',
		overDepositOrder : '',
		noDepositOrder : ''
      },
      //客户组织
      deptList: [],
      //客户分类
      customerTypeList: [],
      //客户小分类
      customerTypeChildrenList: [],
      //业务员
      bizList: [],
      customerKindList: [{ no: '1', label: '渠道店' }, { no: '2', label: '加盟店' }, { no: '3', label: '代加工' }],
      provinceList: province,
      // 被选中的市数据
      cityList: [],
      // 被选中的县数据
      areaList: [],
      orderQtys: [100, 200, 300, 400, 500, 600, 700, 800],
      selectProvince: {},
      selectCity: {},
      selectArea: {},
      //价格策略
      priceStrategyList: [],
      //物流
      wuliuList: [],

      //收款条件
      shoukuanList: [],
      //客户所属公司
      companyList: [],

      //审批权限
      approvedPermiss: false,
      //报表查看权限
      reportViewPermiss: false,

      //是否禁用起订量
      orderQtyDisabled: false,

      //是否启用用费
      freightFeeDisabled: true,

      rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入用户名' },
          {
            required: true,
            trigger: 'blur',
            validator: checkUserNumber,
          },
        ],
        organizationCode: [
          { required: true, trigger: 'blur', message: '请选择客户组织' },
        ],
        customerTypeCode: [
          { required: true, trigger: 'blur', message: '请选择客户分类' },
        ],
        // customerTypeChildCode: [
        //   { required: true, trigger: 'blur', message: '请选择客户小分类' },
        // ],
        bizCode: [
          { required: true, trigger: 'blur', message: '请选择业务人员' },
        ],
        principal: [
          { required: true, trigger: 'blur', message: '请输入负责人姓名' },
        ],
        phoneNumber: [
          { required: true, trigger: 'blur', message: '请输入手机号码' },
          {
            required: true,
            trigger: 'blur',
            validator: checkPhoneNumber,
          },
        ],
        wuliuCode: [
          { required: true, trigger: 'blur', message: '请输入物流线路' },
        ],
        shoukuanCode: [
          { required: true, trigger: 'blur', message: '请输入收款条件' },
        ],
        companyCode: [
          { required: true, trigger: 'blur', message: '请输入客户所属公司' },
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入密码' },
          { validator: validatePass, trigger: 'blur' },
        ],
        passwordConfirm: [
          { required: true, trigger: 'blur', message: '请再次输入密码' },
          { validator: validatePass2, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      let res = await getDept()
      this.deptList = res
      //客户组织
      /*this.form.organizationCode = '100'
      this.form.organizationName = this.organizationList.find(
        (p) => p.fnumber == this.form.organizationCode
      ).fname*/

      res = await getCustomerLastTypeList()
      this.customerTypeList = res

      //客户大分类
      // res = await getCustomerTypeList()
      // this.customerTypeList = res
      /*this.form.customerTypeCode = 100788
      this.form.customerTypeName = this.customerTypeList.find(
        (p) => p.fid == this.form.customerTypeCode
      ).fname*/

      // //加载小分类
      // await this.selectCustomerType(this.form.customerTypeCode)

      //获取审批通过的价格策略

      this.priceStrategyList = await getApprovedList()

      //物流路线
      this.wuliuList = await getWuliuList()

      //收款信息
      this.shoukuanList = await getShoukuanList()

      //客户所属公司
      this.companyList = await getCompanyList()

      //会员信息
      const { customerInfo } = this.$route.params
      if (customerInfo) {
        //删除验证规则
        this.rules.password = []
        this.rules.passwordConfirm = []

        this.form = Object.assign({}, customerInfo)

        //类型转换
        // this.form.customerTypeCode = customerInfo.customerTypeCode

        //根据大分类获取到小分类
        // const res = await getCustomerTypeChildrenList(
        //   this.form.customerTypeCode
        // )
        // this.customerTypeChildrenList = res
        // this.form.customerTypeChildCode = customerInfo.customerTypeChildCode

        //业务员
        await this.selectDept()
        this.form.bizCode = customerInfo.bizCode
        this.form.bizName = customerInfo.bizName

        //设置省市区
        this.selectProvince =
          this.provinceList.find((o) => o.id == this.form.province) || {}

        //市
        if (this.selectProvince) {
          this.cityList = this.selectProvince.children
          if (this.cityList) {
            this.selectCity = this.cityList.find((o) => o.id == this.form.city)
          }
        }

        //区
        if (this.selectCity) {
          this.areaList = this.selectCity.children
          if (this.areaList) {
            this.selectArea = this.areaList.find(
              (o) => o.id == this.form.district
            )
          }
        }

        this.approvedPermiss = false
        this.reportViewPermiss = false
        //审批权限
        if ((this.form.permiss & approvedPermiss) == approvedPermiss) {
          this.approvedPermiss = true
        }

        //报表查看权限
        if ((this.form.permiss & reportViewPermiss) == reportViewPermiss) {
          this.reportViewPermiss = true
        }
		
		//预付款金额 锁定金额
		this.form.depositAmount = customerInfo.depositAmount
		this.form.lockAmount  = customerInfo.lockAmount
      }
    },
    //客户
    // async selectCustomerType(event) {
    //   this.customerTypeChildrenList = []
    //   this.form.customerTypeChildCode = ''
    //   this.form.customerTypeChildName = ''
    //
    //   //业务员
    //   this.bizList = []
    //   this.form.bizCode = ''
    //   this.form.bizName = ''
    //
    //   if (event) {
    //     const res = await getCustomerTypeChildrenList(event)
    //     this.customerTypeChildrenList = res
    //     if (res.length > 0) {
    //       this.form.customerTypeChildName = res[0].fname
    //       this.form.customerTypeChildCode = res[0].fnumber
    //       //获取业务员
    //       this.bizList = await getBizList(res[0].fname,this.form.organizationCode)
    //     }
    //   }
    // },
    //小分类
    async selectDept() {
      this.bizList = []
      this.form.bizCode = ''
      this.form.bizName = ''

      if (this.form.organizationCode) {
        //获取业务员
        for(let i = 0; i < this.deptList.length; i++) {
          let dept = this.deptList[i]
          if (dept.fnumber === this.form.organizationCode) {
            this.bizList = await getBizList(dept.fname)
            break
          }
        }
      }
    },
    selectProvinceFun(event) {
      if (event) {
        this.cityList = event.children
      } else {
        this.cityList = []
      }
      this.areaList = []
      this.selectArea = {}
    },
    selectCityFun(event) {
      this.selectArea = {}
      if (event) {
        this.areaList = event.children
      } else {
        this.areaList = []
      }
    },
    selectOrderQty(event) {
      if (event) {
        this.freightFeeDisabled = true
        this.freight = 0
        this.freightFee = ''
      }
    },
    selectFreightCheckBox(event) {
      this.orderQtyDisabled = event
      this.freightFeeDisabled = !event
    },
    onSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let _this = this
          //根据code反查客户组织名
          let result = this.$baseLodash.find(this.deptList, (o) => {
              return o.fnumber === this.form.organizationCode
            }
          )
          this.form.organizationName = result ? result.fname : ''

          //根据类别code反查类别名
          result = this.$baseLodash.find(this.customerTypeList, (o) => {
            return o.fnumber === this.form.customerTypeCode
          })
          this.form.customerTypeName = result ? result.fname : ''

          // if (this.customerTypeChildrenList.length > 0) {
          //   //根据类别code反查小分类别名
          //   result = this.$baseLodash.find(
          //     this.customerTypeChildrenList,
          //     function (o) {
          //       return o.fnumber == _this.form.customerTypeChildCode
          //     }
          //   )
          //   this.form.customerTypeChildName = result ? result.fname : ''
          // }

          //根据业务code反查名
          result = this.$baseLodash.find(this.bizList, function (o) {
            return o.fnumber == _this.form.bizCode
          })
          this.form.bizName = result ? result.fname : ''

          //根据业务code反查名
          result = this.$baseLodash.find(this.customerKindList, function (o) {
            return o.no == _this.form.customerKindCode
          })
          this.form.customerKindName = result ? result.label : ''

          result = this.$baseLodash.find(this.wuliuList, function (o) {
            return o.fnumber == _this.form.wuliuCode
          })
          this.form.wuliuName = result ? result.fdataValue : ''


          result = this.$baseLodash.find(this.shoukuanList, function (o) {
            return o.fnumber == _this.form.shoukuanCode
          })
          this.form.shoukuanName = result ? result.fname : ''

          result = this.$baseLodash.find(this.companyList, function (o) {
            return o.fnumber == _this.form.companyCode
          })
          this.form.companyName = result ? result.fdatavalue : ''

          let data = null
          this.form.province = this.selectProvince.id
          this.form.city = this.selectCity.id
          this.form.district = this.selectArea.id
          let permiss = 0
          if (this.approvedPermiss) {
            permiss += approvedPermiss
          }
          if (this.reportViewPermiss) {
            permiss += reportViewPermiss
          }
          this.form.permiss = permiss
          this.form.customerTypeChildCode = 'none'
          this.form.customerTypeChildName = 'none'
          if (this.form.id) {
            data = await doEdit(this.form)
          } else {
            data = await doAdd(this.form)
          }
          this.$baseMessage('提交完成', 'success')
          this.$emit('fetch-data')
        } else {
          return false
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 40%;
}

.address {
  ::v-deep .el-select {
    width: 100%;
  }
}
.address {
  display: flex;
  div {
    margin-right: 5px;
  }
}
</style>
